package com.bing.jetty;

import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.eclipse.jetty.webapp.WebAppContext;
import org.junit.Test;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by kaibb on 15-11-4.
 */
public class HelloJetty {
    @Test
    public void hello() throws Exception {
        Server server = new Server(8080);
        Handler handler = new AbstractHandler() {
            @Override
            public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
                response.setContentType("text/html; charset=utf-8");
                response.setStatus(HttpServletResponse.SC_OK);
                response.getWriter().println("<h1>Hello World</h1>");
                baseRequest.setHandled(true);
            }
        };
        server.setHandler(handler);
        server.start();
        server.join();
    }


    @Test
    public void helloEmbeded() throws Exception {
        Server server = new Server(8080);
        WebAppContext webContext = new WebAppContext();

        webContext.setDescriptor(getClass().getResource("WebApp/WEB-INF/web.xml").toString());
        webContext.setResourceBase(getClass().getResource("WebApp/jsp").toString());
        webContext.setServer(server);
        webContext.setParentLoaderPriority(true);
        server.setHandler(webContext);
        server.start();
        server.join();
    }
}
